/*
 * Copyright (c) 2020-2021, SERI Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-29     Lyons        first version
 */

#include "__def.h"
#include "systick.h"
#include "gpio.h"
#include "timer.h"
#include "uart.h"
#include "xprintf.h"

// #define TEST_RTOS
// #define TEST_UART
// #define TEST_LCD

#ifdef TEST_RTOS
#include "rtthread.h"
#endif // #ifdef TEST_RTOS

#ifdef TEST_LCD
#include "Driver_tftspi.h"
#include "Task_tft.h"
#endif // #ifdef TEST_LCD

#ifdef TEST_RTOS
#define DELAY_MS(t) rt_thread_mdelay(t)
#else
#define DELAY_MS(t) delay_ms(t)
#endif // #ifdef TEST_RTOS

int main()
{
#ifdef TEST_UART
    int sum;
    int mul;
    int div;

    sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    xprintf("add:  1+2+..+100 = %5d, expect: %5d\n", sum,  5050);

    sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum -= i;
    }
    xprintf("sub: -1-2-..-100 = %5d, expect: %5d\n", sum, -5050);

    mul = 1;
    for (int i = 1; i <= 8; i++) {
        mul *= i;
    }
    xprintf("mul:  1*2*..*8   = %5d, expect: %5d\n", mul,  40320);

    div = 19960214;
    for (int i = 1; i <= 8; i++) {
        div /= i;
    }
    xprintf("div:  %d, expect: %d\n", div, 495);
#endif // #ifdef TEST_UART

#ifdef TEST_LCD
    TFT_InitConfig();

    TFT_Select(0xff, 1);
    TFT_DisplaySTR(0, 0, &DefaultStyle, "Hello, World!");

    TFT_Select(0xff, 0);
#endif // #ifdef TEST_LCD

#ifdef TEST_RTOS
    timer_init(TIM1, CPU_FREQ_MHZ-1, (1000/RT_TICK_PER_SECOND)*1000); // tick = 1ms
    timer_control(TIM1, TIM_EN);
#endif // #ifdef TEST_RTOS

    while (1)
    {
        POut(0,1);
        DELAY_MS(500);
        POut(0,0);
        DELAY_MS(500);
    }

    return 0;
}

void timer1_handler(void)
{
#ifdef TEST_RTOS
    rt_enter_critical();

    extern void rt_os_tick_callback(void);
    rt_os_tick_callback();

    rt_exit_critical();
#endif // #ifdef TEST_RTOS
}
